package sm.upgrade;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;

import sm.codec.type.Logical;
import sm.upgrade.api.UpgradePhase;
import sm.util.RADFunction;
import sm.util.SMMap;
import sm.util.Util;

public class ConfigMgmtEnvUpgrade implements UpgradePhase {

	private static Logger logger = LoggerFactory.getLogger(UpgradePhase.class);

	private HibernateTemplate template;

	public void setTemplate(HibernateTemplate template) {
		this.template = template;
	}

	@Override
	public void upgrade() {
		logger.info("Updating Configuration Management environment record...");

		Object icmEnv = template.get("environment", "inventory management");
		if (icmEnv != null) {
			SMMap icmEnvMap = (SMMap) icmEnv;
			icmEnvMap.put("cm3SubscriptionAdd", "Subscription");
			icmEnvMap.put("cm3SubscriptionRemove", "Subscription");
			template.update("environment", icmEnv);
		}

		// apm.upgrade.views
		String[] inboxClasses = new String[] { "classList",
				"com.peregrine.eclipse.chart",
				"com.peregrine.eclipse.chart.dashboard" };

		for (String inboxClass : inboxClasses) {
			List<Object> inboxes = template.find(
					"from inbox where inbox_class = ?", inboxClass);
			if (inboxes != null) {
				for (Object inbox : inboxes) {
					SMMap inboxMap = (SMMap) inbox;
					if ("classList".equals(inboxClass)) {
						inboxMap.put("navLaunch", RADFunction.nullsub(
								inboxMap.get("navLaunch"), "recordList"));
						if (Util.isNull(inboxMap.get("viewtype"))
								|| "recordList".equals(inboxMap
										.get("navLaunch"))) {
							List<Object> sorts = (List<Object>) inboxMap
									.get("sort");
							List<Object> sortBys = (List<Object>) inboxMap
									.get("sortBy");

							if (sorts != null) {
								int size = sorts.size();
								for (int i = 0; i < size; i++) {
									String sort = (String) sorts.get(i);
									SMMap sortBy = new SMMap();
									if (sortBys != null) {
										sortBy = (SMMap) sortBys.get(i);
										sortBy.put("showSortField",
												Logical.TRUE);
									}
									sortBy.put("sortFieldName", sort);
									sortBy.put("sortType", "ascending");
								}
							}
						}
						inboxMap.put("viewtype", RADFunction.nullsub(
								inboxMap.get("viewtype"), "Table"));
					} else if ("com.peregrine.eclipse.chart".equals(inboxClass)) {
						inboxMap.put("inbox_class", "chart");
					} else if ("com.peregrine.eclipse.chart.dashboard"
							.equals(inboxClass)) {
						inboxMap.put("inbox_class", "dashboard");
					}
					template.update("inbox", inboxMap);
				}
			}
		}

		logger.info("  Finished updating Configuration Management environment record.");
	}
}
